<?php

namespace App\B2BProject;

use Illuminate\Database\Eloquent\Model;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class AttachmentPrivateFiles extends Model
{
    use AttachmentPrivateFileRouteGetterTrait;

    protected $fillable = ['sha512', 'extension', 'local_path', 'mime_type', 'original_name', 'size'];

    /**
     * 创建一个私有文件对象
     *
     * @param UploadedFile $file
     * @param string       $path 文件修正路径，该路径务必以 / 打头
     *
     * @return AttachmentPrivateFiles
     */
    public static function setNewUploadFile(UploadedFile $file, $path = '')
    {
        if ($file->isValid()) {
            $sha512    = hash_file('sha512', $file->getPathname());
            $extension = $file->guessClientExtension();
            $localName = md5($sha512) . '_' . time() . '.' . $extension;
            $mime      = $file->getMimeType();
            $origin    = $file->getClientOriginalName();
            $size      = $file->getSize();

            $target = trim(str_replace(base_path(), '',
                $file->move(base_path('storage/app/upload/private_attachment' . $path), $localName)), '\/');

            $new                = new static;
            $new->sha512        = $sha512;
            $new->mime_type     = $mime;
            $new->local_path    = $target;
            $new->extension     = $extension;
            $new->original_name = $origin;
            $new->size          = $size;

            $new->save();
            return $new;
        } else {
            throw new FileException('Upload error');
        }
    }

    /**
     * 读取并写入 OUTPUT 流
     */
    public function readToBuffer()
    {
        $file = new \SplFileObject(base_path($this->local_path), 'r');

        $fd = fopen('php://output', 'w');

        while (!$file->eof()) {
            fwrite($fd, $file->fread(1024));
        }

        fclose($fd);
    }
}
